<template>
	<div class="app-container">
		<jk-card ref="box1" class="margin-bottom-10">
			<div class="stop-machine-header">
				<div class="flex-start-center">
					<div class="realtime-tile">
						<div class="realtime-icon"></div>
						<span>实时监控</span>
					</div>
					<el-tag effect="plain" size="mini" type="info" class="margin-left-10" style="font-weight: 400;font-size: 14px;">
						<span class="el-icon-time item-gap"></span>
						<span class="">{{ currentTime }}</span>
					</el-tag>
				</div>
				<div class="flex-start-center">
					<div class="item-gap"><el-button :loading="tableLoading" size="mini" icon="el-icon-refresh" type="primary" @click="getTotalChartData"></el-button></div>
					<jk-full-screen-button @status="onFullScreenChange"></jk-full-screen-button>
				</div>
			</div>
			<el-row style="height: 180px;" :gutter="16">
				<el-col :span="8" style="height: 100%;">
					<chartView :chart-data="totalChartData" style="height: 100%;"></chartView>
				</el-col>
				<el-col :span="16" style="height: 100%;">
					<el-row class="process-legend" :gutter="14">
						<el-col
							v-for="(processItem, processIndex) in totalChartData.machineProcessShutdownList"
							:key="processIndex"
							style="height: 100%;"
							:span="6"
						>
							<div
								class="process-item"
								:class="processItem.processCode === searchParams.processCode ? 'active-process' : ''"
								@click="onSelectProcessChange(processItem)"
							>
								<div class="process-item-label">
									<span>{{ processItem.processName }}</span>
								</div>
								<div class="process-item-count-box">
									<div class="process-item-val">{{ processItem.shutdownCount || 0 }}</div>
									<span class="process-item-unit">/{{ processItem.processMachineNum }}台</span>
								</div>
								<div class="process-item-type-box">
									<div
										v-for="(item) in processItem.machineShutdownTypeList"
										:key="item.id"
										class="process-item-type-item"
									>
										<div class="flex-start-center">
											<div class="process-item-type-item-state" :style="{background: setColor(item.typeId)}"></div>
											<span>{{ item.typeName }}</span>
										</div>
										<div class="flex-start-center">
											<div :style="{color: setColor(item.typeId)}">{{ item.machineCount || 0 }}</div>
											<span>台</span>
										</div>
									</div>
								</div>
							</div>
						</el-col>
					</el-row>
				</el-col>
			</el-row>
		</jk-card>

		<jk-card>
			<div ref="box3" class="flex-between-center-wrap">
				<div class="flex-start-center-wrap"></div>
				<div class="flex-end-center-wrap">
					<shortcutDateTime v-model="searchParams.dateTimeRange" class="margin-bottom-4" :type="shortType"></shortcutDateTime>
					<jk-date-picker
						v-model="searchParams.dateTimeRange"
						:picker-options="pickerOptions"
						type="datetimerange"
						clearable
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						size="small"
						style="width: 380px"
						class="margin-bottom-4 item-gap"
						@change="onTimeChange"
					></jk-date-picker>
					<jk-select v-model="searchParams.workshopId" clearable placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-bottom-4 item-gap"></jk-select>
					<jk-select v-model="searchParams.typeId" clearable placeholder="停机类型" :option-list="stopTypeList" size="small" class="search-bar-item-size2 margin-bottom-4 item-gap"></jk-select>
					<jk-select v-model="searchParams.shutdownState" clearable placeholder="停机状态" :option-list="stopStateList" size="small" class="search-bar-item-size1 margin-bottom-4 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" size="small" class="search-bar-item-size2 margin-bottom-4 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button class="margin-bottom-4" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
			<listView
				:data-list="tableData"
				:height="isFull ? tableHeight + 114 : tableHeight + 20"
			></listView>
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatTime, pageConfig } from '/src/utils/jk/jk-tool';
    import handlerCache from '../../../mixins/handler-cache';
    import listView from './components/list-view';
    import chartView from './components/chart-view';
    import {
        productionMachineShutdownRecordsMachinePage,
        productionMachineShutdownRecordsMonitor
    } from '../../../api/production/reports';
    import { stopStateList, stopTypeList } from '../../../utils/jk/status-option-list';
    import shortcutDateTime from './components/shortcat-date-time';
    export default {
        name: 'MachineStopAnalysis',
        components: {
            shortcutDateTime,
            chartView,
            listView
        },
        mixins: [calHeight, handlerCache],
        data() {
            return {
                prefix: 'production:productUseCommunication',
                apiItem: {
                    'page': productionMachineShutdownRecordsMachinePage
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                shortType: null,
                currentTime: '',
                importDialogState: false,
                dataId: null,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                workshopList: [],
                totalCount: 0,
                stopTypeList: stopTypeList,
                stopStateList: stopStateList,
                isFull: false,
                totalChartData: {
                    machineShutdownTypeList: [],
                    machineProcessShutdownList: []
                },
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    processCode: null,
                    machineNameOrCode: '',
                    stopType: null,
                    shutdownState: 0,
                    dateTimeRange: []
                },
                timer: {},
                timer2: {}
            };
        },
        methods: {
            onTimeChange() {
                this.shortType = null;
            },
            setColor(id) {
                return this.stopTypeList.find(x => x.id === id) ? this.stopTypeList.find(x => x.id === id).color : '';
            },
            onFullScreenChange(e) {
                this.isFull = e;
            },
            onSelectProcessChange(e) {
                if (Object.keys(this.searchParams).length && this.searchParams.processCode === e.processCode) {
                    this.$set(this.searchParams, 'processCode', '');
                } else {
                    this.$set(this.searchParams, 'processCode', e.processCode);
                }
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onVisibleChangeOfImportDialog(e) {
                this.importDialogState = e;
            },
            onFinishBtnOfImportDialog() {
                this.importDialogState = false;
                this.getListRequest();
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            /** 查询列表 */
            getListRequest() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.dateTimeRange && params.dateTimeRange.length) {
                    params.beginTime = params.dateTimeRange[0];
                    params.endTime = params.dateTimeRange[1];
                }
                delete params.dateTimeRange;
                this.tableLoading = true;
                this.apiItem.page(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getTotalChartData() {
                this.tableLoading = true;
                return productionMachineShutdownRecordsMonitor().then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        resData.machineProcessShutdownList = resData.machineProcessShutdownList.filter(x => {
                            if (!['XS', 'CS'].includes(x.processCode)) {
                                x.machineShutdownTypeList = x.machineShutdownTypeList.filter(k => [1, 2, 3, 4].includes(k.typeId));
                            }
                            return x;
                        });
                        this.totalChartData = resData;
                    }
                });
            },
            runData() {
                this.getDependentData();
                this.clearTimer();
                this.timer = setInterval(() => {
                    this.getDependentData();
                }, 5000);
            },
            runTime() {
                this.getDependentData();
                this.clearTimer();
                this.currentTime = formatTime(Date.now());
                this.timer2 = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            clearTimer() {
                clearInterval(this.timer2);
                clearInterval(this.timer);
            },
            async getDependentData() {
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getTotalChartData();
                await this.getListRequest();
            }
        },
        mounted() {
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.runData();
                _this.runTime();
            });
        },
        beforeRouteLeave(to, from, next) {
            this.clearTimer();
            next();
        }
    };
</script>
<style scoped lang="scss">
    .stop-machine-header {
        font-size: 22px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
        margin-bottom: 10px;
        .realtime-tile {
            display: flex;
            align-items: center;
            color: #515a6e;
            .realtime-icon {
                width: 5px;
                height: 5px;
                border-radius: 50%;
                background: #19be6b;
                margin-right: 4px;
                animation: myAn 2s infinite;
            }
        }
    }
    @keyframes myAn {
        0%{
            opacity: 1;
        }
        50%{
            opacity: 0;
        }
        100%{
            opacity: 1;
        }
    }
    .process-legend {
        width: 100%;
        height: 100%;
        .process-item {
            width: 100%;
            height: 100%;
            border: solid 1px #dcdee2;
            margin: 0 10px 10px 10px;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            box-sizing: border-box;
            .process-item-label {
                height: 42px;
                border-bottom: solid 1px #dcdee2;
                font-size: 16px;
                background: #e8eaec;
                display: flex;
                justify-content: center;
                align-items: center;
                flex-direction: column;
                color: #515a6e;
            }
            .process-item-type-box {
                padding: 4px 10px 0 10px;
                box-sizing: border-box;
                .process-item-type-item {
                    font-size: 12px;
                    color: #808695;
                    margin: 1px 0;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .process-item-type-item-state {
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        margin: 0 4px;
                    }
                }
            }
            .process-item-count-box {
                display: flex;
                justify-content: center;
                align-items: flex-end;
                margin-top: 6px;
                .process-item-val {
                    font-size: 22px;
                    color: #515a6e;
                }
                .process-item-unit {
                    color: #808695;
                    font-size: 12px;
                    margin-left: 4px;
                }
            }
        }
        .process-item:hover {
            box-shadow: 0 0 2px 1px #2d8cf0;
            border: solid 1px #2d8cf0;
        }
        .active-process {
            border: solid 1px #19be6b;
            box-shadow: 0 0 2px 1px #19be6b;
            transition: all .2s;
        }
    }
</style>
